from django.shortcuts import render, HttpResponse, redirect
from .models import StudentInfo


# Create your views here.
def info_add(request):
    if request.method == 'GET':
        return render(request, 'info_add.html')

    elif request.method == 'POST':
        # 获取用户提交的数据
        username = request.POST.get('username')
        age = request.POST.get('age')
        address = request.POST.get('address')
        hobby = request.POST.getlist('hobby')
        hobby = ','.join(hobby)
        grade = request.POST.get('grade')
        # print(hobby)
        # 添加到数据库
        StudentInfo.objects.create(username=username, age=age, address=address, hobby=hobby, grade=grade)

    # 自动跳转
    return redirect('/info/list/')


def info_list(request):
    """ 搜索功能 """
    data_dict = {}
    search_data = request.GET.get('q', '')
    if search_data:
        data_dict['username__contains'] = search_data
    data_list = StudentInfo.objects.filter(**data_dict)
    print(data_list)
    return render(request, 'info_list.html', {'data_list': data_list,'search_data': search_data,})


def info_delete(request):
    nid = request.GET.get('nid')

    StudentInfo.objects.filter(id=nid).delete()

    return redirect('/info/list/')


def info_edit(request, nid):
    # 根据nid,获取他的数据
    row_object = StudentInfo.objects.filter(id=nid).first()
    id = row_object.id
    if request.method == "GET":
        username = row_object.username
        age = row_object.age
        address = row_object.address
        grade = row_object.grade
        hobby = row_object.hobby
        print(id, username, age, address, grade, hobby)
        return render(request, 'info_edit.html', locals())
    elif request.method == "POST":
        # 获取用户提交的数据
        username = request.POST.get('username')
        age = request.POST.get('age')
        address = request.POST.get('address')
        hobby = request.POST.getlist('hobby')
        hobby = ','.join(hobby)
        grade = request.POST.get('grade')
        # print(hobby)
        # 更新到数据库
        StudentInfo.objects.filter(id=id).update(
            username=username, age=age, address=address, hobby=hobby, grade=grade
        )
        return redirect('/info/list/')

